<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\admin\controller;
use think\Request;
use think\Log;
use mip\AdminApiBase;

class ApiAdminUpload extends AdminApiBase
{
    public function defaultImgUpload(Request $request)
    {
        $arr =  $this->_fileupload($request,'image','jpg,png,gif');

        if($arr['code'] ==1){
            return jsonSuccess($arr['msg'],$arr['fileurl']);
        }else{
            return jsonError($arr['msg']);
        }
    }
    public function defaultobjmtlUpload(Request $request)
    {
        $arr =  $this->_fileupload($request,'Obj','obj,mtl');
        if($arr['code'] ==1){
            return jsonSuccess($arr['msg'],$arr['fileurl']);
        }else{
            return jsonError($arr['msg']);
        }
    }
    public function defaultVideoUpload(Request $request)
    {
        $arr =  $this->_fileupload($request,'video','mp4');
        if($arr['code'] ==1){
            return jsonSuccess($arr['msg'],$arr['fileurl']);
        }else{
            return jsonError($arr['msg']);
        }
    }

    public function defaultAudioUpload(Request $request)
    {
        $arr = $this->_fileupload($request,'audio','mp3,wav,wma,m4a');
        if($arr['code'] ==1){
            return jsonSuccess($arr['msg'],$arr['fileurl']);
        }else{
            return jsonError($arr['msg']);
        }
    }

    public function simImgUpload(Request $request)
    {
        $arr = $this->_fileupload($request,'simeditor','jpg,png,gif,mp3,wav,wma,m4a');

        $arrSim = [];
        if($arr['code']==1){
            $arrSim['success']=true;
            $arrSim['msg'] = '文件上传成功';
            $arrSim['file_path'] = $arr['fileurl'];
        }else{
            $arrSim['success']=false;
            $arrSim['msg'] = $arr['msg'];
        }

        return json_encode($arrSim);
    }

    public function defaultFileUpload(Request $request)
    {
        if (Request::instance()->isPost()) {
            $arr = $this->_fileupload($request,'file',null);
            if($arr['code'] ==1){
                return jsonSuccess($arr['msg'],$arr['fileurl']);
            }else{
                return jsonError($arr['msg']);
            }
        }
    }

    public function list_img()
    {
        if (Request::instance()->isPost()) {
            $pagesize = input('pagesize');
            $pagenumb = input('pagenumb');

            // 获取uid
            $header = Request::instance()->header();
            $uid = $header['uid'];

            $files = db('fileUpload')->where('uid',$uid)->whereOr('uid','')->order('create_time desc')->page($pagenumb,$pagesize)->select();

            // 总数量
            $cnt = db('fileUpload')->where('uid',$uid)->whereOr('uid','')->count();

            $rows = [];
            foreach ($files as $k1=>$v1) {
                $fileTitle = empty($v1['file_title'])?'飞鸟图片':$v1['file_title'];
                $rows[] = ['imgId' => $v1['id'], 'imgUrl' => $v1['file_url'] , 'imgTitle' => $fileTitle];
            }
            $page =['count' => $cnt, 'rows'=> $rows ];
            return jsonSuccess('查询成功', $page);
        }
    }

    public function del_img(){
        if (Request::instance()->isPost()) {

            $id = input('id');
            $fu = db('fileUpload')->where('id',$id)->find();

            // 先删除文件
            $realPath = (MIP_HOST ? ROOT_PATH :PUBLIC_PATH).$fu['file_save_path'];
            unlink($realPath);

            $arrid = explode(',',$id);
            foreach($arrid as $k=>$v){
                db('fileUpload')->where('id',$v)->delete();
            }

            return jsonSuccess('图片删除成功');
        }
    }

    private function _fileupload(Request $request,$type='image',$ext='jpg,png,gif'){
        if (Request::instance()->isPost()) {
            // 参数type
            $type = input('post.type');
            $fileTitle = input('post.fileTitle');

            // 字段名
            $file = $request->file('fileDataFileName');
            if (empty($type)) {
                $type = 'image';
            }
            if (empty($file)) {
                $arr['code']=109;
                $arr['msg'] ='上传文件不存在，请确认file name 的值为 fileDataFileName ';
                return $arr;
            }

            // 获取uid
            $header = Request::instance()->header();
            $uid = $header['uid'];

            if(empty($fileTitle)){
                $fileTitle = $file->getInfo()['name'];
            }

            // 获取mime
            $mime = $file->getMime();

            // 日期路径
            $datePath =  DS . date('Y', time()) . DS . date('m', time()) . DS . date('d', time());
            // 文件存储相对路径
            $relaPath =  DS . 'uploads' . DS . $type .$datePath;

            // 如果是MIP_HOST方式，即根路径为项目根,false，根路径在public下。
            if (MIP_HOST) {
                if(empty($ext)){
                    $info = $file->rule('uniqid')->move(ROOT_PATH .$relaPath);
                }else {
                    $info = $file->rule('uniqid')->validate(['ext' => $ext])->move(ROOT_PATH . $relaPath);
                }
            } else {
                if(empty($ext)){
                    $info = $file->rule('uniqid')->move(PUBLIC_PATH .$relaPath);
                }else{
                    $info = $file->rule('uniqid')->validate(['ext' => $ext])->move(PUBLIC_PATH .$relaPath);
                }

            }

            // 获取文件后缀
            $fileExt = substr(strrchr($info->getFilename(),'.'),1);
            // 获取文件大小
            $fileSize =$info->getSize();

            $arr=[];
            if ($info) {
                $fileurl = $relaPath . DS . $info->getFilename();

                $fu=['uid'=>$uid,'file_type'=>$type,'file_ext'=>$fileExt,'file_url'=>$fileurl ,'file_url' => $fileurl ,'file_save_path' => $fileurl,
                    'file_size'=>$fileSize,'file_title'=>$fileTitle, 'create_time'=> date('Y-m-d H:i:s',time())
                ,'mime'=>$mime];
                $fid = db('fileUpload')->insert($fu);

                $fu['id'] = $fid;

                $arr['code']=1;
                $arr['msg'] ='';
                $arr['fileurl'] = $fileurl;
                $arr['fileinfo'] = $fu;
            } else {
                $arr['code']=105;
                $arr['msg'] =$file->getError();
            }
            return $arr;
        }
    }


}